<template>

<div class="user_filter_rule">
  <div class="headers_connect">
      <div class="headers_lf">
        <img :src="$ossLink+'/app/mspbots_theme_icon/pageheader/usesr_filter_rules.png'"
              alt="">
        <!-- <span v-if="nextTicketType.replace('dataset','')  === 'autotask'">{{$t('statement.ufrfat')}}</span>
        <span v-if="nextTicketType.replace('dataset','')  === 'nextTicket'">{{$t('statement.ufrfcw')}}</span>
        <span v-if="nextTicketType.replace('dataset','')  === 'syncro'">{{$t('statement.syncro')}}</span>
        <span v-if="nextTicketType.replace('dataset','')  === 'kaseyabms'">{{$t('statement.kaseyabms')}}</span> -->
        <span>{{$route.query.name}}</span>
        <div>
          <view-linked-info :linkKey="'UserManagement'"></view-linked-info>
        </div>
        </div>
    </div>
  <el-card shadow="never"
           class="aui-card--fill">
    <div>
      <div style="margin-bottom:15px">
        <el-popover
          ref="filterPOP"
          popper-class="pop_for_nextticket"
          placement="bottom"
          width="280"
          @show="showFilter"
          @hide="closePop"
          trigger="click">
          <div style="border-bottom:1px solid #ddd">
            <div style="height:30px;display:flex;justify-content:space-between;padding:20px;margin-bottom:10px">
              <div style="font-weight:700;font-size:16px">{{$t('custom.nextTicket.baf')}}</div>
              <div style="font-size:16px;" @click="closePop" class="el-icon-close cursor_pointer icon_close"></div>
            </div>
          </div>
          <div  style="padding:20px" v-loading="filterLoading">
            <div>{{$t('custom.nextTicket.fl')}}</div>
            <el-select collapse-tags clearable multiple filterable v-model="filterValue" style="width:100%" :placeholder="$t('custom.component.gadget.placeholder')">
              <el-option
                v-for="item in filterOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <el-button @click="saveFilter" size="mini" type="primary" style="width:100%;margin-top:15px">{{$t('custom.nextTicket.apl')}}</el-button>
          </div>
          <el-button slot="reference"
                        size="small" type="primary">{{ $t('custom.nextTicket.baf') }}</el-button>
        </el-popover>
        <el-popover style="margin-left:10px"
          popper-class="pop_for_nextticket"
          placement="bottom"
          width="280"
          ref="templatePOP"
          @show="showTemplate"
          @hide="closeTemplatePop"
          trigger="click">
          <div style="border-bottom:1px solid #ddd">
            <div style="height:30px;display:flex;justify-content:space-between;padding:20px;margin-bottom:10px">
              <div style="font-weight:700;font-size:16px">{{$t('custom.nextTicket.bat')}}</div>
              <div style="font-size:16px;" @click="closeTemplatePop" class="el-icon-close cursor_pointer icon_close"></div>
            </div>
          </div>
          <div  style="padding:20px" v-loading="templateLoading">
            <div>{{$t('custom.nextTicket.tl')}}</div>
            <el-select collapse-tags filterable v-model="templateValue" style="width:100%" :placeholder="$t('custom.component.gadget.placeholder')">
              <el-option
                v-for="item in templateOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <el-button @click="saveTemplate" size="mini" type="primary" style="width:100%;margin-top:15px">{{$t('custom.nextTicket.apl')}}</el-button>
          </div>
          <el-button slot="reference"
                        size="small" type="primary">{{ $t('custom.nextTicket.bat') }}</el-button>
        </el-popover>
      </div>
      <div class="control-section">
        <div class="content-wrapper"
             v-loading="dataListLoading">
          <ejs-grid :dataSource="userList"
                    :allowResizing="gridDefaultSetting.allowResizing"
                    :allowFiltering="gridDefaultSetting.allowFiltering"
                    :filterSettings="gridDefaultSetting.filterSettings"
                    :allowGrouping="gridDefaultSetting.allowGrouping"
                    :allowPaging="gridDefaultSetting.allowPaging"
                    :toolbar="toolbar"
                    :editSettings="gridDefaultSetting.editSettings"
                    :allowTextWrap="gridDefaultSetting.allowTextWrap"
                    :showColumnChooser="gridDefaultSetting.showColumnChooser"
                    :allowReordering="gridDefaultSetting.allowReordering"
                    :allowSorting="gridDefaultSetting.allowSorting"
                    :sortSettings='gridDefaultSetting.initialSort'
                    :allowExcelExport="gridDefaultSetting.allowExcelExport"
                    :allowPdfExport="gridDefaultSetting.allowPdfExport"
                    ref="userfiltergrid"
                    :toolbarClick='toolbarClick'
                    :pdfQueryCellInfo="queryCellInfo"
                    :excelQueryCellInfo="queryCellInfo"
                    :height='gridHeight'
                    :selectionSettings="gridDefaultSetting.selectOptions"
                    :commandClick="commandClick"
                    :pageSettings="gridDefaultSetting.pageSettings">
            <e-columns>
              <e-column type="checkbox"
                        :allowFiltering="false"
                        :allowSorting="false"
                        width="46"
                        ></e-column>
              <e-column field="userName"
                        :headerText="$t('user.username')"
                        ></e-column>
              <e-column field="realName"
                        :headerText="$t('user.realName')"
                        ></e-column>
              <e-column field="managerName"
                        :headerText="$t('user.managerName')"
                        width="120"
                        :template="ManagerFormat"></e-column>
              <e-column field='jobTitle'
                        :visible='true'
                        :headerText="$t('user.jobTitle')"
                        width='200'>
              </e-column>
              <e-column :template="FilterTemplate"
                        textAlign='Right'
                        :autoFit="true"
                        :headerText="$t('custom.nextTicket.dntf')"
                        ></e-column>
              <e-column :template="TemplateTemplate"
                        textAlign='Right'
                        :autoFit="true"
                        :headerText="$t('custom.nextTicket.dntt')"
                        ></e-column>
            </e-columns>
          </ejs-grid>
          <!-- <el-pagination background
                         :layout="pageOptions.layout"
                         @current-change="pageCurrentChangeHandle"
                         @size-change="pageSizeChangeHandle"
                         :page-sizes="$store.state.app.pageOptions.pageSizes"
                         :pager-count="$store.state.app.pageOptions.pageCount"
                         :current-page="pageOptions.currentPage"
                         :total="pageOptions.total">
          </el-pagination> -->
        </div>
      </div>
    </div>
  </el-card>

</div>

</template>

<script>
import Vue from 'vue'
import { getNextAppInfo } from '@/utils/common'
import { exportFilterRuleCvs } from '@/utils/exportPdfCvs'
import ManagerFormat from '@/views/modules/sys/components/ManagerFormat'
export default {
  props: {
    // nextTicketType: {
    //   type: String,
    //   default: ''
    // }
  },
  data () {
    return {
      gridHeight: 800,
      ManagerFormat: function () {
        return { template: ManagerFormat }
      },
      FilterTemplate: function () {
        return { template: FilterTemplate }
      },
      TemplateTemplate: function () {
        return { template: TemplateTemplate }
      },
      gridDefaultSetting: {
        allowResizing: true,
        allowFiltering: true,
        showColumnMenu: true,
        filterSettings: {
          type: 'Excel'
        },
        allowGrouping: false,
        allowPaging: false,
        toolbar: ['Search', 'ColumnChooser'],
        allowExcelExport: true,
        allowPdfExport: true,
        showColumnChooser: true,
        groupOptions: {
          columns: ['name']
        },
        allowReordering: true,
        allowSorting: true,
        allowTextWrap: true,
        height: window.innerHeight - 230,
        groupSettings: {
          allowReordering: false,
          columns: [],
          disablePageWiseAggregates: false,
          enableLazyLoading: false,
          showDropArea: true,
          showGroupedColumn: false,
          showToggleButton: false
        },
        selectOptions: {
          checkboxOnly: true
        },
        pageSettings: { pageSize: 200, pageSizes: [10, 50, 100, 200, 1000], pageCount: 4 },
        initialSort: {
          columns: [{ field: 'roleList', direction: 'Ascending' },
            { field: 'upn', direction: 'Ascending' }]
        }
      },
      toolbar: ['PdfExport', 'CsvExport', 'Search', 'ColumnChooser'],
      filterValue: [],
      templateValue: '0',
      filterOptions: [],
      templateOptions: [],
      userList: [],
      dataListLoading: false,
      filterLoading: false,
      templateLoading: false,
      nextTicketType: this.$route.params.afterId
    }
  },

  created () {
    this.gridHeight = document.documentElement.clientHeight - 350
    Vue['_this_nextTicket_vue'] = this
    this.dataListLoading = true
    Promise.all([
      this.getNextTicketTemplateList(),
      this.queryFilterOptions()
    ]).then(() => {
      this.getUserList()
    })
  },
  beforeDestroy () {
    // delete Vue['_this_nextTicket_vue']
  },
  methods: {
    showTemplate () {
      let selectList = this.$refs.userfiltergrid.getSelectedRecords()
      if (!(selectList && selectList.length > 0)) {
        this.$refs.templatePOP.doClose()
        this.$message.error(this.$t('custom.nextTicket.psu'))
      }
    },
    showFilter () {
      let selectList = this.$refs.userfiltergrid.getSelectedRecords()
      if (!(selectList && selectList.length > 0)) {
        this.$refs.filterPOP.doClose()
        this.$message.error(this.$t('custom.nextTicket.psu'))
      }
    },
    commandClick (type, row, value) {
      if (type === 'EditFilter') {
        let params = {
          type: this.nextTicketType,
          userIds: [row.userId],
          filterIds: value
        }
        this.dataListLoading = true
        this.$interface.nextTicket.saveNextTicketFilterForUser(params).then(({ data: res }) => {
          this.dataListLoading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            this.$message.success(res.msg)
            this.getUserList()
          }
        }).catch((e) => {
          this.dataListLoading = false
          this.$message.error(e.msg)
        })
      } else if (type === 'EditTemplate') {
        let params = {
          type: this.nextTicketType,
          userIds: [row.userId],
          modelId: value[0]
        }
        this.dataListLoading = true
        this.$interface.nextTicket.saveNextTicketTemplateForUser(params).then(({ data: res }) => {
          this.dataListLoading = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data) {
            this.$message.success(res.msg)
            this.getUserList()
          }
        }).catch((e) => {
          this.dataListLoading = false
          this.$message.error(e.msg)
        })
      }
    },
    saveFilter () {
      let suerArr = this.$refs.userfiltergrid.getSelectedRecords()
      if (!suerArr || suerArr.length === 0) {
        return this.$message.error(this.$t('custom.nextTicket.psu'))
      }
      let params = {
        type: this.nextTicketType,
        userIds: suerArr.map(i => i.userId),
        filterIds: this.filterValue
      }
      this.filterLoading = true
      this.$interface.nextTicket.saveNextTicketFilterForUser(params).then(({ data: res }) => {
        this.filterLoading = false
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (res.data) {
          this.$message.success(res.msg)
          this.closePop()
          this.getUserList()
        }
      }).catch((e) => {
        this.filterLoading = false
        this.$message.error(e.msg)
      })
    },
    saveTemplate () {
      if (this.templateValue.length === 0) {
        return this.$message.error(this.$t('custom.nextTicket.pst'))
      }
      let suerArr = this.$refs.userfiltergrid.getSelectedRecords()
      if (!suerArr || suerArr.length === 0) {
        return this.$message.error(this.$t('custom.nextTicket.psu'))
      }
      let params = {
        type: this.nextTicketType,
        userIds: suerArr.map(i => i.userId),
        modelId: this.templateValue
      }
      this.templateLoading = true
      this.$interface.nextTicket.saveNextTicketTemplateForUser(params).then(({ data: res }) => {
        this.templateLoading = false
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (res.data) {
          this.$message.success(res.msg)
          this.closeTemplatePop()
          this.getUserList()
        }
      }).catch((e) => {
        this.templateLoading = false
        this.$message.error(e.msg)
      })
    },
    async getNextTicketTemplateList () {
      const params = {
        type: this.nextTicketType
      }
      const { data: res } = await this.$interface.nextTicket.getNextTicketTemplateList(params)
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      if (res.data.length >= 0) {
        res.data.forEach(item => {
          item.id = item.id.toString()
        })
        res.data.unshift({
          name: 'Default Template',
          id: '0'
        })
        this.templateOptions = res.data
      }
    },
    async queryFilterOptions () {
      let params = {
        gadgetId: getNextAppInfo('nextTicketType', 'gadgetId'),
        type: this.nextTicketType
      }
      // if (this.nextTicketType.replace('dataset','')  === 'autotask') {
      //   params = {
      //     gadgetId: '8a265b05-93cc-4d16-852b-dab33d7536df',
      //     type: 'autotask'
      //   }
      // } else if (this.nextTicketType.replace('dataset','')  === 'nextTicket') {
      //   params = {
      //     gadgetId: 'next-ticket-setting-filter-list',
      //     type: 'nextTicket'
      //   }
      // } else if (this.nextTicketType.replace('dataset','')  === 'syncro') {
      //   params = {
      //     gadgetId: 'df93de1e-0048-4b77-9bad-09bbbc324ec2',
      //     type: 'syncro'
      //   }
      // } else if (this.nextTicketType.replace('dataset','')  === 'kaseyabms') {
      //   params = {
      //     gadgetId: 'a221c328-da89-4b3b-b01b-9af5f4f2fdae',
      //     type: 'kaseyabms'
      //   }
      // }
      const { data: res } = await this.$interface.nextTicket.getNextTicketOptions(params, this.nextTicketType)
      if (res.code !== 0) {
        return this.$message.error(res.msg)
      }
      if (res.data) {
        this.filterOptions = res.data
      }
    },
    closePop () {
      this.$refs.filterPOP.doClose()
      this.filterValue = []
    },
    closeTemplatePop () {
      this.$refs.templatePOP.doClose()
      this.templateValue = '0'
    },
    getUserList () {
      let params = {
        type: this.nextTicketType
      }
      this.dataListLoading = true
      this.userList = []
      this.$interface.nextTicket.getNextTicketUserListApi(params).then(({ data: res }) => {
        this.dataListLoading = false
        if (res.code !== 0) {
          return this.$message.error(res.msg)
        }
        if (res.data) {
          res.data.forEach(item => {
            item.option = JSON.parse(JSON.stringify(this.filterOptions))
            item.templateOption = JSON.parse(JSON.stringify(this.templateOptions))
            item.option.push({})
            item.templateOption.push({})
            if (!item.modelId) {
              item.modelId = '0'
            }
          })
          this.userList = res.data
        }
      }).catch((e) => {
        this.$message.error(e.msg)
        this.dataListLoading = false
      })
    },
    toolbarClick (args) {
      switch (args.item.text) {
        case 'PDF Export':
          (this.$refs['userfiltergrid']).pdfExport()
          break
        case 'Excel Export':
          (this.$refs['userfiltergrid']).excelExport()
          break
        case 'CSV Export':
          {
            let selectFields=[
              {alias:'User Name',field:'userName'},
              {alias:'Real Name',field:'realName'},
              {alias:'Manager',field:'managerName'},
              {alias:'Job Title',field:'jobTitle'},
              {alias:'Default Next Ticket Filter',field:'dntf'},
              {alias:'Default Next Ticket Template',field:'dntt'},
            ]
            let userList=this.userList.map(v=>{
              v.dntf=Array.isArray(v.filterIds)?v.filterIds.map(i=>v.option.find(item=>item.id===i).name).join(','):''
              v.dntt=Array.isArray(v.templateOption)?v.templateOption.find(item=>item.id===v.modelId).name:''
              return v
            })
            // (this.$refs['userfiltergrid']).csvExport()
            exportFilterRuleCvs(userList,selectFields)
            break
          }
      }
    },
    queryCellInfo (args) {
      try {
        if(args.column.headerText === 'Default Next Ticket Filter'){
          args.value=Array.isArray(args.data.filterIds)?args.data.filterIds.map(v=>args.data.option.find(item=>item.id===v).name).join(','):''
        }
        if(args.column.headerText === 'Default Next Ticket Template'){
          args.value=Array.isArray(args.data.templateOption)?args.data.templateOption.find(item=>item.id===args.data.modelId).name:''
        }
      } catch (error) {
        console.log(error);
      }
    }
  }
}
const FilterTemplate = Vue.component(
  'user-btn', {
    template: `<div><el-select ref="select" @change="changeHander" style="position: relative;width:100%" collapse-tags multiple clearable filterable @visible-change="change" v-model="filterValue">
              <el-option
                v-for="(item,index) in $data.data.option"
                :key="item.id"
                :disabled="index===$data.data.option.length-1"
                :label="item.name"
                :value="item.id">
              </el-option>
              <div style="position: absolute;bottom:0;right:0;">
                <el-button size="mini" style="margin:0 10px 10px;float:right" plain type="primary" @click="clickSelect('EditFilter',$data.data,filterValue)">Apply</el-button>
                <el-button size="mini" style="margin-bottom:10px;float:right" plain type="primary" @click="cancel">Cancel</el-button>
              </div>
            </el-select></div>`,
    data () {
      return {
        filterValue: [],
        isEdit: false
      }
    },
    mounted () {
      this.init()
    },
    methods: {
      changeHander (val) {
        // this.filterValue = val.slice(val.length - 1)
        // if (this.filterValue.length === 0) {
        //   this.filterValue = []
        // }
      },
      cancel () {
        this.$refs.select.blur()
        this.init()
      },
      change (val) {
        if (!val && !this.isEdit) {
          this.init()
        }
      },
      init () {
        this.isEdit = false
        this.filterValue = this.$data.data.filterIds
      },
      clickSelect (e, row, filterValue) {
        Vue['_this_nextTicket_vue'].commandClick(e, row, filterValue)
        this.isEdit = true
        this.$refs.select.blur()
      }
    }
  }
)
const TemplateTemplate = Vue.component(
  'user-btn', {
    template: `<div><el-select ref="select" multiple style="position: relative;width:100%" collapse-tags @change="changeHander" clearable filterable @visible-change="change" v-model="templateValue">
              <el-option
                v-for="(item,index) in $data.data.templateOption"
                :key="item.id"
                :disabled="index===$data.data.templateOption.length-1"
                :label="item.name"
                :value="item.id">
              </el-option>
              <div style="position: absolute;bottom:0;right:0;">
                <el-button size="mini" style="margin:0 10px 10px;float:right" plain type="primary" @click="clickSelect('EditTemplate',$data.data,templateValue)">Apply</el-button>
                <el-button size="mini" style="margin-bottom:10px;float:right" plain type="primary" @click="cancel">Cancel</el-button>
              </div>
            </el-select></div>`,
    data () {
      return {
        templateValue: [],
        isEdit: false
      }
    },
    mounted () {
      this.init()
    },
    methods: {
      changeHander (val) {
        this.templateValue = val.slice(val.length - 1)
        if (this.templateValue.length === 0) {
          this.templateValue = ['0']
        }
      },
      cancel () {
        this.$refs.select.blur()
        this.init()
      },
      change (val) {
        if (!val && !this.isEdit) {
          this.init()
        }
      },
      watch: {
        templateValue (val) {
          if (!val) {
            val = ['0']
          }
        }
      },
      init () {
        this.isEdit = false
        this.templateValue = this.$data.data.modelId && [this.$data.data.modelId]
      },
      clickSelect (e, row, templateValue) {
        Vue['_this_nextTicket_vue'].commandClick(e, row, templateValue)
        this.isEdit = true
        this.$refs.select.blur()
      }
    }
  }
)
</script>
<style lang="scss">
.el-select-dropdown__item.is-disabled {
    color: #C0C4CC;
    cursor: auto;
}
.pop_for_nextticket.el-popover {
  padding:0!important;
}
.user_filter_rule {
  .headers_connect {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 48px;
    background: #ffffff;
    box-shadow: 0px 0px 8px 0px #f0f0f0;
    border-radius: 4px;
    border: 1px solid rgba(0, 0, 0, 0.01);
    margin-bottom: 10px;
    .headers_lf {
      display: flex;
      align-items: center;
      font-size: 20px;
      font-weight: 600;
      color: rgba(0, 0, 0, 0.75);
    }
    .headers_rg {
      .cuifont {
        font-size: 14px;
        cursor: pointer;
      }
    }
    img {
      width: 20px;
      height: 20px;
      margin-right: 10px;
    }
  }
}
</style>
<style lang="scss" scoped>
::v-deep .e-icon-descending {
  margin:-26px 28px -29px 0!important
}
::v-deep .e-icon-ascending {
  margin:-27px 28px -29px 0!important
}
::v-deep .e-sortnumber {
  margin:4px 27px 0 2px !important
}
.icon_close:hover {
  color: $--theme-color
}
</style>
